package com.cloud.logger.zchain.zchainclient.interceptor;

import com.cloud.logger.zchain.core.common.util.StreamUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * 不兼容requestMap请求
 * User: wcy
 * Date: 2017/4/14
 * Time: 9:56
 */
public class WrapperRequest extends HttpServletRequestWrapper {

    private byte[] requestBody = null;

    public WrapperRequest(HttpServletRequest request){

        super(request);

        //缓存请求body
        requestBody = HttpHelper.getBodyString(request).getBytes(Charset.forName("UTF-8"));
    }

    /**
     * 重写 getInputStream()
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {
        if(requestBody == null){
            requestBody= new byte[0];
        }
        final ByteArrayInputStream bais = new ByteArrayInputStream(requestBody);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return bais.read();
            }
        };
    }

    /**
     * 重写 getReader()
     */
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

}
